package com.yeswater.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmCallback;
import com.yeswater.rabbitmq.utils.RabbitmqUtil;
import com.yeswater.rabbitmq.utils.SleepUtil;

import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;

/**
 * 消息确认
 * Author : yeswater
 */

public class ConfirmMessage {

    public static final int MESSAGE_COUNT = 50;

    public static void main(String[] args) throws Exception {
        // 耗时: 1090ms
        // publishMessageIndividually();

        // 耗时: 83ms
        // publishMessageBatch();

        // 耗时: 7ms
        publishMessageAsync();
    }

    /**
     * 单个确认
     */
    public static void publishMessageIndividually() throws Exception {
        Channel channel = RabbitmqUtil.getChannel();
        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName, true, false, false, null);
        channel.confirmSelect();
        long start = System.currentTimeMillis();

        // 批量发消息
        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String message = i + "";
            channel.basicPublish("", queueName, null, message.getBytes(StandardCharsets.UTF_8));
            // 发送单个消息就进行发布确认
            boolean flag = channel.waitForConfirms();
            if (flag) {
                System.out.println("发布消息成功: " + message);
            }
        }

        long end = System.currentTimeMillis();

        System.out.println("耗时: " + (end - start) + "ms");
    }

    /**
     * 批量确认
     */
    public static void publishMessageBatch() throws Exception {
        Channel channel = RabbitmqUtil.getChannel();
        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName, true, false, false, null);
        channel.confirmSelect();
        long start = System.currentTimeMillis();

        int batchSize = 10;
        // 批量发消息
        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String message = i + "";
            channel.basicPublish("", queueName, null, message.getBytes(StandardCharsets.UTF_8));
            // 发送10个消息进行发布确认
            if ((i + 1) % batchSize == 0) {
                boolean flag = channel.waitForConfirms();
                if (flag) {
                    System.out.println("发布消息成功数量: " + (i + 1));
                }
            }
        }

        long end = System.currentTimeMillis();

        System.out.println("耗时: " + (end - start) + "ms");
    }

    /**
     * 异步确认
     */
    public static void publishMessageAsync() throws Exception {
        Channel channel = RabbitmqUtil.getChannel();
        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName, true, false, false, null);
        channel.confirmSelect();

        /**
         * 线程安全有序的 hash表 <序号,消息> ,适合高并发的情况
         * 1. 将序号与消息进行关联
         * 2. 批量删除消息
         * 3. 支持高并发
         */
        ConcurrentSkipListMap<Long, String> outConfirms = new ConcurrentSkipListMap<>();

        ConfirmCallback ackCallback = (deliveryTag, multiple) -> {
            System.out.println("multiple: "+multiple);
            // 2. 删除未确认的消息
            if (multiple) {
                ConcurrentNavigableMap<Long, String> confirmedMessage = outConfirms.headMap(deliveryTag);
                confirmedMessage.clear();
            }else {
                outConfirms.remove(deliveryTag);
            }
            System.out.println("确认的消息: " + deliveryTag);
        };

        ConfirmCallback nackCallback = (deliveryTag, multiple) -> {
            String message = outConfirms.get(deliveryTag);
            // 3. 打印未确认的消息
            System.out.println("未确认的消息: " + message + "未确认的消息标记: " + deliveryTag);
        };


        // 监听器 监听成功和失败的消息
        channel.addConfirmListener(ackCallback, nackCallback);

        long start = System.currentTimeMillis();

        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String message = i + "";
            channel.basicPublish("", queueName, null, message.getBytes(StandardCharsets.UTF_8));
            // SleepUtil.sleep(1);
            // 1. 记录所有要发送的消息的综合
            outConfirms.put(channel.getNextPublishSeqNo(), message);
        }
        long end = System.currentTimeMillis();

        System.out.println("耗时: " + (end - start) + "ms");
    }

}
